import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:huajianshe_app/base/AppNavigator.dart';
import 'package:huajianshe_app/base/BaseState.dart';
import 'package:huajianshe_app/common/App.dart';
import 'package:huajianshe_app/common/AppRouter.dart';
import 'package:huajianshe_app/common/C.dart';
import 'package:huajianshe_app/common/TS.dart';
import 'package:huajianshe_app/common/load_image.dart';
import 'package:huajianshe_app/common/space.dart';
import 'package:huajianshe_app/constants/constant.dart';
import 'package:huajianshe_app/network/Api.dart';
import 'package:huajianshe_app/pages/circle/model/CircleModel.dart';
import 'package:huajianshe_app/pages/user_info/LeaveMessageDialog.dart';
import 'package:huajianshe_app/pages/user_info/UserInfoAppBar.dart';
import 'package:huajianshe_app/utils/SpUtil.dart';
import 'package:huajianshe_app/utils/dialog_util.dart';
import 'package:huajianshe_app/utils/toast_utils.dart';
import 'package:huajianshe_app/widget/AutoGridWidget.dart';
import 'package:huajianshe_app/widget/AutoGridWidgetV2.dart';
import 'package:huajianshe_app/widget/AvatarWidget.dart';
import 'package:huajianshe_app/widget/BgImageLayout.dart';
import 'package:huajianshe_app/widget/RoundedCornerWidget.dart';
import 'package:huajianshe_app/widget/SimpleScrollView.dart';
import 'package:huajianshe_app/widget/SmartButton.dart';
import 'package:oktoast/oktoast.dart';
import 'UserInfoWithButtonItem.dart';
import 'model/UserModel.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';

///他人主页
class UserInfoPage extends StatefulWidget {

  // final int momentType;
  final UserInfo? userInfo;
  final CircleInfo? circleInfo;

  const UserInfoPage(this.userInfo, {
    Key? key,
    this.circleInfo
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _UserInfoPageState();
  }
}

class _UserInfoPageState extends BaseState<UserInfoPage> {

  late SystemUiOverlayStyle overlayStyle;
  late double appbarOpacity;
  late ScrollController controller;
  late int offset = 0;
  UserHomeData? userHomeData;

  @override
  void initState() {
    super.initState();
    overlayStyle = SystemUiOverlayStyle.light;
    appbarOpacity = 0;
    controller = ScrollController();
    controller.addListener(() => {_onScroll()});
    load();
  }

  void load() {
    var data = {
      'member_sn': widget.userInfo?.memberSn,//'306ca1b8723c2736d350fafe08e6a40e', //
      'circle_id': widget.circleInfo?.blogId,//1  //
    };
    print('data: $data');
    sendReq(Api.getUserInfo(), UserHomeResp(), data: data);
  }

  @override
  void onReqSuccess<T>(T t, int code, String msg, String path) {
    super.onReqSuccess(t, code, msg, path);
    if (t is UserHomeResp) {
      print('ok');
      userHomeData = t.data;
      setState(() => {});
    } else if (t is HxCreateAccountResp) {
      if (code == 0) {
        String myHxPwd = SpUtil.getString(Constant.KEY_IM_PWD);
        print('myHxPwd:$myHxPwd');
        if (myHxPwd == '') {
          print('saveHxId: ${t.data?.meHxId} ${t.data?.meHxPwd}');
          App.saveHxId(t.data?.meHxId, t.data?.meHxPwd);
        }
        userHomeData?.userInfo?.hxId = t.data?.otherHxId;
        chat(t.data?.otherHxId);
      } else {
        Toast.show(msg);
      }
    }
  }

  void _onScroll() {
    // print('position ${controller.position} offset ${controller.offset}');
    int newOffset = controller.offset.toInt() - 50;
    if (newOffset > 50) newOffset = 50;
    if (newOffset < 0) newOffset = 0;
    if (offset == newOffset) return;
    offset = newOffset;
    this.appbarOpacity = offset.toDouble() * 2 * 0.01;
    print('appbarOpacity ${appbarOpacity} offset ${offset}');
    if (this.appbarOpacity > 0.5 && this.overlayStyle != SystemUiOverlayStyle.dark) {
      this.overlayStyle = SystemUiOverlayStyle.dark;
    }
    if (this.appbarOpacity <= 0.5 && this.overlayStyle != SystemUiOverlayStyle.light) {
      this.overlayStyle = SystemUiOverlayStyle.light;
    }
    setState(() { });
  }

  @override
  Widget build(BuildContext context) {
     return
       BgImageLayout(imageHeight: 175, imageUrl: 'bg_user_info', bgColor: Colors.white, overlayStyle: overlayStyle, children: [
           SimpleScrollView(controller: controller, children: [
             H(124),
             SizedBox(width: double.infinity, child: Stack(children: [
               Padding(padding: EdgeInsets.only(top: 24), child:
                 Row(mainAxisSize: MainAxisSize.max, children: <Widget>[
                   Expanded(child:
                     RoundedCornerWidget(width: double.infinity, backgroundColor: C.grayF6, borderColor: Colors.transparent,
                      radius: 13, cornerPosition: 3, child:
                      Column(mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.start,
                          children: [...buildUserInfo()]),
                      )
                   )
                 ]),
               ),
              //头像
              Positioned(left: 16, child: AvatarWidget(userHomeData?.userInfo?.avatar ?? '', 66, 0, 0))
            ])),
             ColoredBox(color: C.grayF6, child:
               RoundedCornerWidget(backgroundColor: Colors.white, radius: 13, cornerPosition: 3, width: double.infinity,
                   borderColor: Colors.transparent,
                   child: Column(mainAxisSize: MainAxisSize.max, children: buildBottom())
               )
             ),
              // H(60), Text('11'), H(60), Text('22'), H(60), Text('33'),
              // H(60), Text('44'), H(60), Text('55'), H(60),
           ],
            bottomView: (widget.userInfo?.isFriend == 1) ?
              Padding(padding: EdgeInsets.symmetric(vertical: 12, horizontal: 22), child: SmartButton(
                text: '删除好友', textColor: C.gray1A, fontSize: 15, backgroundColor: Colors.white, height: 44, width: double.infinity,
                radius: 22, borderColor: Colors.transparent, boxShadowList: [
                      BoxShadow(color: Color.fromRGBO(0x00, 0x00, 0x00, 0.04), offset: Offset(0, 1), blurRadius: 10, spreadRadius: 0)
                    ]
              )) : null,
          ),
           //app bar1
          SafeArea(child: Container(height: 48, child: GestureDetector(onTap: () { AppNavigator.pop(context); },
              child: Padding(padding: EdgeInsets.all(15), child: LoadImage('ic_white_arrow', width: 9, height: 16,))
          ))),

           //app bar2
           Opacity(opacity: appbarOpacity, child: Container(color: Color.fromRGBO(255, 255, 255, 1), width: double.infinity, child:
             SafeArea(child: UserInfoAppBar(userInfo: widget.userInfo, circleId: widget.circleInfo?.circleId,))
           ))
        ]
      );
  }

  List<Widget> buildUserInfo() {
    return [
      H(9),
      Row(mainAxisSize: MainAxisSize.max, children: [
        Spacer(),
        SmartButton(text: userHomeData?.userInfo?.isFriend == 1 ? '聊天' : '留言', height: 32, width: 72,
          onPressed: chatOrMessage, radius: 16, drawableLeft: LoadImage('ic_message'), drawablePadding: 3,),
        W(15)
      ]),
      H(10),
      Row(mainAxisSize: MainAxisSize.min, children: [
        W(15),
        Text(userHomeData?.userInfo?.nickname ?? '', style: TS(18, C.gray333)),
        W(3.5)
      ]),
      H(3),
      Row(mainAxisSize: MainAxisSize.min, children: [
        W(15),
        Text('昵    称: ${userHomeData?.userInfo?.realname}', style: TS(13, C.gray666),),
      ]),
      H(3),
      Row(mainAxisSize: MainAxisSize.min, children: [
        W(15),
        Text('微信号: ${userHomeData?.userInfo?.wechatNo ?? ''}', style: TS(13, C.gray666),),
        W(3),
        if (userHomeData?.userInfo?.hasExchangeWechat != 1)
          SmartButton(text: '交换', fontSize: 7, radius: 2, width: 30, height: 12, backgroundColor: Color.fromRGBO(0xf7, 0xe7, 0xe7, 1),
              textColor: C.primary, drawableLeft: LoadImage('ic_exchange'), drawablePadding: 2, onPressed: exchangeWechat)
      ]),
      H(3),
      Row(mainAxisSize: MainAxisSize.min, children: [
        W(15),
        Text('手机号: ${userHomeData?.userInfo?.mobile ?? ''}', style: TS(13, C.gray666),),
        if (userHomeData?.userInfo?.hasExchangeMobile != 1)
          SmartButton(text: '交换', fontSize: 7, radius: 2, width: 30, height: 12, backgroundColor: Color.fromRGBO(0xf7, 0xe7, 0xe7, 1),
            textColor: C.primary, drawableLeft: LoadImage('ic_exchange'), drawablePadding: 2, onPressed: exchangeMobile,)
      ]),
      H(3),
      Row(mainAxisSize: MainAxisSize.min, children: [
        W(15),
        Text('所属公司: ${userHomeData?.userInfo?.companyName}-${userHomeData?.userInfo?.positionName}', style: TS(13, C.gray666)),
      ]),
      H(3),
      // Row(mainAxisSize: MainAxisSize.max, children: [
      //  W(15),
      Padding(padding: EdgeInsets.only(left: 15, right: 15, bottom: 15), child:
        Text('${userHomeData?.userInfo?.desc ?? ''}',
            style: TS(13, C.gray666), maxLines: 2, overflow: TextOverflow.ellipsis)
      )

    ];
  }

  List<Widget> buildBottom() { // 底部信息
    return [
      if (userHomeData?.userInfo?.isFriend == 1) //如果是好友
        ...[SizedBox(height: 48, child: InkWell(onTap: () => setLabel(),
            child: Row(mainAxisSize: MainAxisSize.max, children: [
              W(15),
              Text('设置备注和标签', style: TS(15,  C.gray1A),),
              Spacer(),
              LoadImage('ic_gray_right_arrow', width: 7,),
              W(15)
            ])
        )),
        PD(0.5, 15, 15)],
      SizedBox(height: 48, child:
        Row(mainAxisSize: MainAxisSize.max, children: [
          W(15),
          Text(widget.circleInfo != null ? '来自圈子' : '共同圈子', style: TS(15,  C.gray1A),), //如果从推荐进来，这里只显示一个带进来的圈子，否则这里放一个箭头，点击后显示全部圈子
          Spacer(),
          widget.circleInfo != null ?
            SmartButton(width: 100, height: 28, backgroundColor: C.grayF6, radius: 14, borderColor: Colors.transparent,
              text: widget.circleInfo!.title ?? '', textColor: C.gray1A, drawableLeft: LoadImage('ic_contacts'), drawablePadding: 3)
          :
            GestureDetector(onTap: jointCircles,
                child: Padding(padding: EdgeInsets.only(left: 10, top: 10, bottom: 10), child: LoadImage('ic_gray_right_arrow'))),
          W(15)
        ]),
      ),
      PD(0.5, 15, 15),
      ...buildPosts(),
      ...buildRecommendations()
    ];
  }

  List<Widget> buildPosts() { // Ta的动态
    if (userHomeData?.latestPosts?.isNotEmpty == true) {
      Widget title = SizedBox(height: 42, child:
        Row(mainAxisSize: MainAxisSize.max, children: [
          W(15),
          Text('Ta的动态', style: TS(15,  C.gray1A)),
          W(4),
          if ((userHomeData?.userInfo?.sex ?? 0 ) > 0) LoadImage('${userHomeData?.userInfo?.sex == 2 ? 'ic_female' : 'ic_male'}'),
        ])
      );
      List<Widget> media = userHomeData!.latestPosts!.map((e) {
        Widget widget = LoadImage(e.url, width: double.infinity, height: double.infinity, holderImg: 'placeholder',);
        if (e.isVideo == 1) {
          widget = Stack(children: [
            widget,
            Center(child: LoadImage('play_20'))
          ]);
        }
        return widget;
      }).toList();
      return [
        title,
        InkWell(onTap: () => hisMoments(), child: Padding(padding: EdgeInsets.symmetric(horizontal: 15),
          child: AutoGridWidgetV2(colNum: 6, radius: 4,
              widgets: media,
              moreView: SmartButton(backgroundColor: C.grayF6, borderColor: Colors.transparent, borderWidth: 0, radius: 4,
                  text: 'More', fontSize: 12, textColor: C.gray333)
          )
        ))
      ];
    }
    return [H(0)];
  }

  List<Widget> buildRecommendations() {
    List<Widget> result = [];
    // if (widget.circleInfo != null) {
      result.add(PD(0.5, 15, 15));
      result.add(H(10));
      result.add(Row(mainAxisSize: MainAxisSize.max, children: [
        W(15),
        Text('看了Ta的人还看了', style: TS(15, C.gray1A)) //todo 性别
      ]));
      if (userHomeData?.watchList?.isNotEmpty == true) {
        for (var r in userHomeData!.watchList!) {
          CircleInfo? circleInfo = (r.circles?.isNotEmpty == true) ? r.circles![0] : null;
          result.add(UserInfoItemWithButton(padding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
              circleInfo: circleInfo, userInfo: r.userInfo));
          result.add(DD(paddingLeft: 15, paddingRight: 15));
        }
      }
    // }
    return result;
  }

  void chatOrMessage() async {
    print('circleId: ${widget.circleInfo}');
    if (userHomeData?.userInfo?.isFriend == 1) { // 好友去聊天 todo
      String hxPwd = userHomeData?.userInfo?.hxPwd ?? '';
      String hxId = userHomeData?.userInfo?.hxId ?? '';
      String myHxPwd = SpUtil.getString(Constant.KEY_IM_PWD);
      if (hxPwd != '' && myHxPwd != '') {
        print('环信id都有，走起');
        chat(hxId);
      } else {
        print('没有环信id');
        sendReq(Api.getHxId(), HxCreateAccountResp(), data: {'member_sn': userHomeData?.userInfo?.memberSn});
      }
    } else { // 非好友去留言
      DialogUtil.showBottomDialogV2(context, LeaveMessageDialog(widget.circleInfo?.circleId), height: 0.8, radius: 13,
          bgColor: Colors.transparent, margin: EdgeInsets.symmetric(horizontal: 5));
    }
  }

  void chat(String? hxId) async {
    print('${EMClient.getInstance.isLoginBefore}');
    EMConversation conv = await EMClient.getInstance.chatManager.getConversation(hxId);
    AppNavigator.push(context, RouteName.CHAT, arguments: {'id': userHomeData?.userInfo?.nickname, 'conv': conv});
  }

  void exchangeWechat() {
    showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('交换微信'),
          content: SingleChildScrollView(
            child: ListBody(
              children: const <Widget>[
                Text('您还没有设置过微信，无法交换'),
              ],
            ),
          ),
          actions: <Widget>[
            TextButton(
              child: Text('好的', style: TS(14, C.primary)),
              onPressed: () { Navigator.of(context).pop(); },
            ),
          ],
        );
      },
    );
  }

  void exchangeMobile() {

  }

  void jointCircles() { // 共同圈子
    if (userHomeData?.circles?.isNotEmpty == true) {
      AppNavigator.push(context, RouteName.JOINT_CIRCLES, arguments: {'circles': userHomeData?.circles});
    }
  }

  void hisMoments() { //他的全部动态
    // userHomeData?.userInfo
    AppNavigator.push(context, RouteName.USER_MOMENTS, arguments: {'momentType': widget.circleInfo == null ? 6 : 5,
      'userInfo': widget.userInfo, 'circleId' : widget.circleInfo});
  }

  void setLabel() {
    AppNavigator.push(context, RouteName.LABEL_SETTING, arguments: {'memberSn': userHomeData?.userInfo?.memberSn});
  }
}